
import axios from 'axios';
import { load } from 'cheerio';

const api = {
  async request(url) {
    // In a real implementation, this would use IPC to send request through main process
    try {
      // Use the IPC bridge to make actual HTTP requests
      return window.electron.request(url);
    } catch (error) {
      console.error('Error making request:', error);
      
      // Fallback to mock data if we have embedded HTML
      console.log('Falling back to mock data...');
      
      if (url.includes('/dy/')) {
        // Use the locally stored HTML files instead
        return {
          data: mockRegionCategoriesHtml + mockRegionDataHtml
        };
      }
      
      throw new Error(`Mock API doesn't support URL: ${url}`);
    }
  }
};

export async function fetchRegionCategories() {
  try {
    const response = await api.request('https://q.10jqka.com.cn/dy/');
    const html = response.data;
    
    const $ = load(html);
    const categories = [];
    
    $('.cate_group').each((i, group) => {
      const letter = $(group).find('.cate_letter').text().trim();
      const regions = [];
      
      $(group).find('.cate_items a').each((j, link) => {
        const name = $(link).text().trim();
        const href = $(link).attr('href');
        const code = href.match(/code\/(\d+)/)[1];
        
        regions.push({
          name,
          code,
          url: href
        });
      });
      
      categories.push({
        letter,
        regions
      });
    });
    
    return categories;
  } catch (error) {
    console.error('Error fetching region categories:', error);
    throw error;
  }
}

export async function fetchRegionData() {
  try {
    const response = await api.request('https://q.10jqka.com.cn/dy/');
    const html = response.data;
    
    const $ = load(html);
    const data = [];
    
    $('.m-table tbody tr').each((i, row) => {
      const cells = $(row).find('td');
      if (cells.length < 12) return;
      const rank = $(cells[0]).text().trim();
      const regionName = $(cells[1]).find('a').text().trim();
      const regionUrl = $(cells[1]).find('a').attr('href');
      const regionCode = regionUrl.match(/code\/(\d+)/)?.[1] || '';
      
      const change = $(cells[2]).text().trim();
      const isNegative = $(cells[2]).hasClass('c-fall');
      
      const volume = $(cells[3]).text().trim();
      const amount = $(cells[4]).text().trim();
      const netflow = $(cells[5]).text().trim();
      const upCount = $(cells[6]).text().trim();
      const downCount = $(cells[7]).text().trim();
      const avgPrice = $(cells[8]).text().trim();
      
      const leadingStock = $(cells[9]).find('a').text().trim();
      const leadingStockUrl = $(cells[9]).find('a').attr('href');
      const latestPrice = $(cells[10]).text().trim();
      const leadingStockChange = $(cells[11]).text().trim();
      
      data.push({
        rank,
        region: {
          name: regionName,
          url: regionUrl,
          code: regionCode
        },
        change: {
          value: change,
          isNegative
        },
        volume,
        amount,
        netflow,
        upCount,
        downCount,
        avgPrice,
        leadingStock: {
          name: leadingStock,
          url: leadingStockUrl,
          latestPrice,
          change: leadingStockChange
        }
      });
    });
    
    return data;
  } catch (error) {
    console.error('Error fetching region data:', error);
    throw error;
  }
}

export function getCategoryUrl(category) {
  const baseUrl = 'https://q.10jqka.com.cn';
  
  switch (category) {
    case 'concept':
      return `${baseUrl}/gn/`;
    case 'region':
      return `${baseUrl}/dy/`;
    case 'industry':
      return `${baseUrl}/thshy/`;
    case 'regulatory':
      return `${baseUrl}/zjhhy/`;
    default:
      return `${baseUrl}/dy/`;
  }
}